package controller;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Window;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.example.remotecontrol.R;
import common.Constant;
import components.AlarmManager;
import components.FragmentMediator;
import components.PasscodeManager;
import components.SMSLogManager;
import components.SMSRecievingCommandFactory;

import data.RCAlertSMSCommand;
import data.RCDeviceSMSCommand;
import data.RCSMSCommand;
import data.RCUpdateSMSCommand;

public class TabNavigation extends SherlockFragmentActivity {

	public static Context RemoteControllerContext = null;
	public static String ACTION_SMS_RECIEVER = "com.example.remotecontrol.action.SMS_RECIEVER";
	public static String ACTION_CHANGE_PASSCODE = "com.example.remotecontrol.action.changepasscode";
	public static String ACTION_CLEAR_PASSCODE = "com.example.remotecontrol.action.clearpasscode";
	private BroadcastReceiver mSMSReciver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			getDataAndHandleRecievedSMS(intent);
		}

		
	};;

	private Fragment[] tabFragment;
	private Integer[] tabTitles = new Integer[] { R.string.action,
			R.string.sms_log, R.string.setting };

	public TabNavigation() {

		RemoteControllerContext = this;

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setTheme(R.style.Theme_MyAppTheme); // Used for theme switching in samples
		requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		super.onCreate(savedInstanceState);

		RemoteControllerContext = this;
		setContentView(R.layout.main_activity);
		// mSelected = (TextView)findViewById(R.id.text);

	
		Intent intent = getIntent();
		getDataAndHandleRecievedSMS(intent);
		

		registerReceiver(mSMSReciver, new IntentFilter(ACTION_SMS_RECIEVER));
		Fragment fragment= FragmentMediator.CreateFragment(FragmentMediator.FRAGMENT_VIEW_PAGER);
		FragmentMediator.transitView(null, fragment, null, false);
//		for (int i = 0; i < 20; i++) {
//		SMSLog smsLog = new SMSLog();
//		smsLog.setDate(new Date());
//		smsLog.setSender("test");
//		smsLog.setContent("body sdfsdf sdf ds fds fffsfd fsdf dsfd f dffd fsdfa fdsfd fds fjsfhjsdfsdjfdsfhdfdhs fds fds fdf a ffd f ds ");
//		SMSLogManager.add(this, smsLog);
//		}
	}

	private void getDataAndHandleRecievedSMS(Intent intent) {
		if (intent != null) {
			String smsContent = intent
					.getStringExtra(common.Constant.BROADCAST_REIEVER_MESSAGE);
			String phone = intent.getStringExtra(common.Constant.BROADCAST_RECIEVER_PHONE_NUMBER);
			if (smsContent != null) {

				// Handle alert
				try {

					handleRecievingSMSCommand(phone, smsContent);

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}

			}

		}
	}
	
	private void handleRecievingSMSCommand(String phoneNumber, String smsContent) {
		RCSMSCommand smsCommand = SMSRecievingCommandFactory.createSMSCommandFromString(phoneNumber, smsContent);
		
		SMSLogManager.sharedSMSLogManager(this).log(this, smsCommand);
		
		if (smsCommand instanceof RCAlertSMSCommand) {
			RCAlertSMSCommand alertSMS = (RCAlertSMSCommand) smsCommand;
			AlarmManager.sharedAlarmList(this).changeAlertState(alertSMS);
			
			//Push to alert list view
			getSupportActionBar().setSelectedNavigationItem(0);

			Fragment alarmFragment = FragmentMediator
					.CreateFragment(FragmentMediator.FRAGMENT_ALARM_OPTION);
			FragmentMediator.transitView(this.tabFragment[0], alarmFragment,
					null, true);
			getSupportFragmentManager().executePendingTransactions();

		} 
		else if (smsCommand instanceof RCDeviceSMSCommand) {
			RCDeviceSMSCommand alertSMS = (RCDeviceSMSCommand) smsCommand;
			AlarmManager.sharedAlarmList(this).changeDeviceState(alertSMS);
			getSupportActionBar().setSelectedNavigationItem(0);

			Fragment deviceFragment = FragmentMediator
					.CreateFragment(FragmentMediator.FRAGMENT_DEVICE_OPTION);
			FragmentMediator.transitView(this.tabFragment[0], deviceFragment,
					null, true);
			getSupportFragmentManager().executePendingTransactions();
		} else if (smsCommand instanceof RCUpdateSMSCommand) {
			RCUpdateSMSCommand alertSMS = (RCUpdateSMSCommand) smsCommand;
			AlarmManager.sharedAlarmList(this).setIsUpdating(false);
			Fragment deviceFragment = FragmentMediator
					.CreateFragment(FragmentMediator.FRAGMENT_DEVICE_OPTION);
			FragmentMediator.transitView(this.tabFragment[0], deviceFragment,
					null, true);
		}

	}

	

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		boolean isExpiredSession = PasscodeManager.sharedPasscode(this)
				.isExpiredSession();

		if (isExpiredSession) {
			Intent newIntent = new Intent(this, PasscodeActivity.class);
			startActivityForResult(newIntent, 0);
		}

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);

		if (arg1 == RESULT_OK) {
			if (arg2 != null) {
				String action = arg2.getAction();

				if (action == null) {

				} else if (action.equals(ACTION_CHANGE_PASSCODE)) {
					Fragment passcode = FragmentMediator
							.CreateFragment(FragmentMediator.FRAGMENT_SET_PASSCODE);
					List<Fragment> fragment = this.getSupportFragmentManager()
							.getFragments();

					FragmentMediator.transitView(
							fragment.get(fragment.size() - 1), passcode, null, true);
				} else if (action.equals(ACTION_CLEAR_PASSCODE)) {
					PasscodeManager.sharedPasscode(this).clearPasscode(this);
					Toast.makeText(this,
							R.string.msg_clear_passcode_successfully,
							Toast.LENGTH_SHORT).show();
				}
			}
		} else if (arg1 == RESULT_CANCELED) {
			//finish();
			//android.os.Process.killProcess(android.os.Process.myPid());
		} else if (arg1 == PasscodeActivity.RESULT_FINISH) {
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	}

	@Override
	public void finish() {
		unregisterReceiver(mSMSReciver);
		super.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		ActionBar actionBar = getSupportActionBar();
		
		switch (actionBar.getSelectedNavigationIndex()) {
		case 0:
			//getSupportMenuInflater().inflate(R.menu.home,  menu);
			menu.clear();
			break;
		case 1:
			getSupportMenuInflater().inflate(R.menu.sms_log_manager,  menu);
			break;
		case 2:
			menu.clear();
			break;
		default:
			break;
		}
		//
		return true;
		
	}
}
